package com.dounine.clouddisk360.parser.deserializer.login;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.dounine.clouddisk360.exception.CloudDiskException;
import com.dounine.clouddisk360.parser.LoginParser;
import com.dounine.clouddisk360.util.URLUtil;

public class LoginResponseHandle implements ResponseHandler<Login> {
	
	private LoginParser loginParser;
	
	public LoginResponseHandle(LoginParser loginParser) {
		this.loginParser = loginParser;
	}

	@Override
	public Login handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity, Consts.UTF_8);
		saveCookie();
		return desializer(result);
	}
	
	public String disassemblyResult(String result) {
		int userinfoIndex = result.indexOf(LoginConst.SPLIT_STR);
		if(userinfoIndex>-1){
			String userInfo = result.substring(userinfoIndex+LoginConst.SPLIT_STR.length(),result.lastIndexOf(";</script>")-2);
			return userInfo;
		}else{
			throw new CloudDiskException("登录失败");
		}
	}

	public Login desializer(String result) {
		if (StringUtils.isNotBlank(result)) {
			result = disassemblyResult(result);
			result = URLUtil.decode(result);
			return JSON.parseObject(result, Login.class);
		}
		return null;
	}
	
	public void saveCookie(){
		loginParser.getCookieStoreUT().writeCookieStoreToDisk(loginParser.getConfig().getBasePath(), loginParser.getHttpClientContext().getCookieStore(),
				LoginConst.COOKIES_NAMES);
	}

}
